package top.happyone.security.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.web.bind.annotation.*;
import top.happyone.security.demo.mapper.AdminMapper;
import top.happyone.security.demo.pojo.Admin;

import java.security.Principal;

@RestController
public class AdminController {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JdbcClientDetailsService clientDetails;

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/getPrincipal")
    public Principal getAdminDetails(Principal principal) {
        return principal;
    }

    @GetMapping("/getAdminDetails")
    public Authentication getAuthentication(Authentication authentication) {
        return authentication;
    }

    @PostMapping("/register")
    public Integer register(@RequestBody Admin admin) {
        return adminMapper.insertSelective(admin.setPassword(passwordEncoder.encode(admin.getPassword())));
    }

    @PostMapping("/addClient")
    public void addClient(@RequestBody BaseClientDetails baseClientDetails) {
        logger.info(baseClientDetails.toString());
        baseClientDetails.setClientSecret(passwordEncoder.encode(baseClientDetails.getClientSecret()));
        clientDetails.addClientDetails(baseClientDetails);

    }


}
